package com.itboye.sunsun.application;

import android.app.Activity;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.support.multidex.MultiDex;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.Toast;

import com.itboye.sunsun.beans.LuntanForumBean.LuntanForumItemBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.me.ui.LanguageSettingUtil;
import com.itboye.sunsun.me.ui.SwitchLanguageObservable;
import com.itboye.sunsun.person.ui.UpdatePhoneActivity;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.web.ui.WebActivity;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.www.aq.base.MyApplication;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class App extends MyApplication {

	public static App ctx;

	private Toast toast;

	public List<WeakReference<Activity>> activityList = new LinkedList<>();

	protected String afterOpen;

	protected String activity;

	protected String extra;

	protected org.json.JSONObject jsonObject2;

	protected String afterOpen2;
	String baseUrl = "http://sunsun.8raw.com/index.php/Webview/index/systemMessage?";

	protected String order_code;

	protected String id;

	protected int type;

	protected JSONObject jsonObject;
	boolean isReadOne, isReadTwo;
	public Vibrator mVibrator;
//	public LocationService locationService;
//	public static ArrayList<LuntanForumItemBean> arrayLisForumItemBeans=new ArrayList<>();
	// 百度地图
//		public BMapManager mBMapMan = null;
	public static ArrayList<LuntanForumItemBean> arrayList=new ArrayList<>();
	// private List<WeakReference<Activity>> activitys = new
	// ArrayList<WeakReference<Activity>>();

	// private UncaughtExceptionHandler exceptionHandler;
	

	
	
	/**
	 * 语言设置工具类
	 * */
	private LanguageSettingUtil languageSetting;

	/**
	 * 语言设置 被观察对象
	 * */
	private SwitchLanguageObservable switchLangObs;
	
	private IWXAPI wxapi;
	public static String WX_APP_ID = "wxabf9bc3a048000ac";
	Intent intent;
	public IWXAPI getWxapi() {
		if(wxapi == null){
			wxapi = WXAPIFactory.createWXAPI(this, WX_APP_ID);
		}
		
		return wxapi;
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}
	
	public static App getInstance() {
		return ctx;
	}
    public boolean m_bKeyRight = true;  
//    BMapManager mBMapManager = null;  

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Thread.setDefaultUncaughtExceptionHandler(new MyUnCatchExceptionHandler());
		super.onCreate();
		ctx = this;
		
//		mBMapMan = new BMapManager(App.ctx);
//		mBMapMan.init(null);
//		locationService = new LocationService(getApplicationContext());
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        if (!"generic".equalsIgnoreCase(Build.BRAND)) {
//            SDKInitializer.initialize(getApplicationContext());
        }
        LanguageSettingUtil.init(this);// 初始化
		languageSetting = LanguageSettingUtil.get();// 检查是否已经初始化
		switchLangObs = new SwitchLanguageObservable();
		// 微信 appid appsecret

		// VolleyExample.main();

		// final Handler handler=new Handler();
		// handler.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// int availableProcessors=Runtime.getRuntime().availableProcessors();
		// DebugToast.show( "availableProcessors: "+availableProcessors, 1);
		// handler.postDelayed(this, 1500);
		// }
		// }, 1500);
		// exceptionHandler=Thread.getDefaultUncaughtExceptionHandler();
		// Thread.setDefaultUncaughtExceptionHandler(new
		// MyUnCatchExceptionHandler());

		initUMengPush();
		   initEngineManager(this); 
		
//		getWxapi().registerApp(WX_APP_ID);
	}
	
	
	 public void initEngineManager(Context context) {  
//	        if (mBMapManager == null) {  
//	            mBMapManager = new BMapManager(context);  
//	        }  
//	  
//	        if (!mBMapManager.init(new MyGeneralListener())) {  
////	            Toast.makeText(DemoApplication.getInstance().getApplicationContext(),   
////	                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();  
//	        }  
	    }  
	      
	
	      
	      
	    // 常用事件监听，用来处理通常的网络错误，授权验证错误等  
//	    static class MyGeneralListener implements MKGeneralListener {  
//	          
//	        @Override  
//	        public void onGetNetworkState(int iError) {  
//	            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {  
//	                Toast.makeText(ctx.getInstance().getApplicationContext(), "您的网络出错啦！",  
//	                    Toast.LENGTH_LONG).show();  
//	            }  
//	            else if (iError == MKEvent.ERROR_NETWORK_DATA) {  
//	                Toast.makeText(ctx.getInstance().getApplicationContext(), "输入正确的检索条件！",  
//	                        Toast.LENGTH_LONG).show();  
//	            }  
//	            // ...  
//	        }  
//	  
//	        @Override  
//	        public void onGetPermissionState(int iError) {  
//	            //非零值表示key验证未通过  
//	            if (iError != 0) {  
//	                //授权Key错误：  
////	                Toast.makeText(DemoApplication.getInstance().getApplicationContext(),   
////	                        "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常！error: "+iError, Toast.LENGTH_LONG).show();  
//	                ctx.getInstance().m_bKeyRight = false;  
//	            }  
//	            else{  
//	                ctx.getInstance().m_bKeyRight = true;  
////	                Toast.makeText(DemoApplication.getInstance().getApplicationContext(),   
////	                        "key认证成功", Toast.LENGTH_LONG).show();  
//	            }  
//	        }  
//	    }  

//	{
		// PlatformConfig.setWeixin("wxa30658c4f4f6bbf4",
		// "69c4d761d4a0801bba64bef359bbf0b2");

//	}

	// public void addActivity(Activity activity) {
	// // activitys.add(new WeakReference<Activity>(activity));
	// }
	public LanguageSettingUtil getLanguageSetting() {
		return languageSetting;
	}

	public SwitchLanguageObservable getSwitchLangObs() {
		return switchLangObs;
	}
	private void initUMengPush() {

		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(true);
		System.out.println("" + "zhixing1");
		UmengMessageHandler messageHandler = new UmengMessageHandler() {
			/**
			 * 参考集成文档的1.6.3 http://dev.umeng.com/push/android/integration#1_6_3
			 * */
			@Override
			public void dealWithCustomMessage(final Context context,
					final UMessage msg) {
				super.dealWithCustomMessage(context, msg);
				System.out.println("dealWithCustomMessage is In ui thread? "
						+ (Looper.getMainLooper() == Looper.myLooper()));
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						System.out.println("" + "zhixing2");
						// TODO Auto-generated method stub
						// 对自定义消息的处理方式，点击或者忽略
						boolean isClickOrDismissed = true;
						if (isClickOrDismissed) {
							System.out.println("msg+" + msg);
							// 自定义消息的点击统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgClick(msg);
						} else {
							System.out.println("" + "zhixing3");
							// 自定义消息的忽略统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
								.show();
					}
				});
			}

			@Override
			public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				super.dealWithNotificationMessage(arg0, arg1);
				if (arg1.activity.equals("bbs_message")) {
					try {
						jsonObject = arg1.getRaw().getJSONObject("extra");
						jsonObject = jsonObject.getJSONObject("after_open");
						type = jsonObject.getInt("type");// ("type");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Intent intent = new Intent("message");
					intent.putExtra("message_type", type);
					if (type == 0)
						SPUtils.put(arg0, null, SPContants.IS_READ_ONE, true);
					else
						SPUtils.put(arg0, null, SPContants.IS_READ_TWO, true);
					sendBroadcast(intent);
					System.out.println(">>>这是推送消息" + arg1.getRaw() + ":"
							+ arg1.extra.get("type"));
				}
			}

			/**
			 * 参考集成文档的1.6.4 http://dev.umeng.com/push/android/integration#1_6_4
			 * */
			@Override
			public Notification getNotification(Context context, UMessage msg) {
				switch (msg.builder_id) {
				case 1:
//					Toast.makeText(App.ctx, "zhixing4", 0).show();
//					System.out.println("执行了sssssssss");
//					NotificationCompat.Builder builder = new NotificationCompat.Builder(
//							context);
//					RemoteViews myNotificationView = new RemoteViews(
//							context.getPackageName(),
//							R.layout.notification_view);
//					myNotificationView.setTextViewText(R.id.notification_title,
//							msg.title);
//					myNotificationView.setTextViewText(R.id.notification_text,
//							msg.text);
//					myNotificationView.setImageViewBitmap(
//							R.id.notification_large_icon,
//							getLargeIcon(context, msg));
//					myNotificationView.setImageViewResource(
//							R.id.notification_small_icon,
//							getSmallIconId(context, msg));
//					builder.setContent(myNotificationView)
//							.setContentTitle(msg.title)
//							.setSmallIcon(getSmallIconId(context, msg))
//							.setContentText(msg.text).setTicker(msg.ticker)
//							.setAutoCancel(true);
//					Notification mNotification = builder.build();
//					// 由于Android
//					// v4包的bug，在2.3及以下系统，Builder创建出来的Notification，并没有设置RemoteView，故需要添加此代码
//					mNotification.contentView = myNotificationView;
//					return mNotification;
					// case 2:
					// NotificationCompat.Builder builder = new
					// NotificationCompat.Builder(context);
					// RemoteViews myNotificationView = new
					// RemoteViews(context.getPackageName(),
					// R.layout.notification_view);
					// myNotificationView.setTextViewText(R.id.notification_title,
					// msg.title);
					// myNotificationView.setTextViewText(R.id.notification_text,
					// msg.text);
					// myNotificationView.setImageViewBitmap(R.id.notification_large_icon,
					// getLargeIcon(context, msg));
					// myNotificationView.setImageViewResource(R.id.notification_small_icon,
					// getSmallIconId(context, msg));
					// builder.setContent(myNotificationView)
					// .setContentTitle(msg.title)
					// .setSmallIcon(getSmallIconId(context, msg))
					// .setContentText(msg.text)
					// .setTicker(msg.ticker)
					// .setAutoCancel(true);
					// Notification mNotification = builder.build();
					// //由于Android
					// v4包的bug，在2.3及以下系统，Builder创建出来的Notification，并没有设置RemoteView，故需要添加此代码
					// mNotification.contentView = myNotificationView;
					// return mNotification;
					// case 3:
					//
				default:
					// 默认为0，若填写的builder_id并不存在，也使用默认。
					return super.getNotification(context, msg);
				}
			}

		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * // 创建一个NotificationManager的引用 NotificationManager notificationManager
		 * = (NotificationManager)
		 * this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		 * 
		 * // 定义Notification的各种属性 Notification notification =new
		 * Notification(R.drawable.icon, "测试", System.currentTimeMillis());
		 * //FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉 //FLAG_NO_CLEAR
		 * 该通知不能被状态栏的清除按钮给清除掉 //FLAG_ONGOING_EVENT 通知放置在正在运行 //FLAG_INSISTENT
		 * 是否一直进行，比如音乐一直播放，知道用户响应 notification.flags |=
		 * Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
		 * notification.flags |= Notification.FLAG_NO_CLEAR; //
		 * 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
		 * notification.flags |= Notification.FLAG_SHOW_LIGHTS; //DEFAULT_ALL
		 * 使用所有默认值，比如声音，震动，闪屏等等 //DEFAULT_LIGHTS 使用默认闪光提示 //DEFAULT_SOUNDS
		 * 使用默认提示声音 //DEFAULT_VIBRATE 使用默认手机震动，需加上<uses-permission
		 * android:name="android.permission.VIBRATE" />权限 notification.defaults
		 * = Notification.DEFAULT_LIGHTS; //叠加效果常量
		 * //notification.defaults=Notification
		 * .DEFAULT_LIGHTS|Notification.DEFAULT_SOUND; notification.ledARGB =
		 * Color.BLUE; notification.ledOnMS =5000; //闪光时间，毫秒
		 * 
		 * // 设置通知的事件消息 CharSequence contentTitle ="标题"; // 通知栏标题 CharSequence
		 * contentText ="内容"; // 通知栏内容
		 * 
		 * //如果需要跳转到指定的Activity，则需要设置PendingIntent
		 * 
		 * Intent notificationIntent =new Intent(A.this, B.class); //
		 * 点击该通知后要跳转的Activity
		 * 
		 * notificationIntent.putExtra("date","需要传递的参数");
		 * 
		 * // FLAG_UPDATE_CURRENT
		 * 更新数据，如果有多个PendingIntent，且requestCode相同，则会替换为最新extra数据
		 * //如果需要通过不同的extra数据，进行处理，就需要requestCode不相同 int requestCode = new
		 * Random().nextInt(); PendingIntent contentItent =
		 * PendingIntent.getActivity(this, requestCode, notificationIntent,
		 * PendingIntent.FLAG_UPDATE_CURRENT);
		 * 
		 * 
		 * 
		 * notification.setLatestEventInfo(this, contentTitle, contentText,
		 * contentItent);
		 * 
		 * // 把Notification传递给NotificationManager notificationManager.notify(0,
		 * notification);
		 */

		/**
		 * 该Handler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK 参考集成文档的1.6.2
		 * http://dev.umeng.com/push/android/integration#1_6_2
		 * */
		UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {
				super.dealWithCustomAction(context, msg);
				Toast.makeText(App.ctx, "执行中国", 0).show();
			}

			@Override
			public void openActivity(Context arg0, UMessage msg) {
				// TODO Auto-generated method stub
				// super.openActivity(arg0, msg);

				if (msg.activity.equals("bbs_message")) {
					try {
						jsonObject = msg.getRaw().getJSONObject("extra");
						jsonObject = jsonObject.getJSONObject("after_open");
						type = jsonObject.getInt("type");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if((SPUtils.get(App.ctx, null, SPContants.LANGUAGE, "").equals(
							"chinese"))){
						 intent = new Intent(App.ctx, UpdatePhoneActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					}else
					
					
					if (type == 0) {
						SPUtils.put(App.ctx, null, SPContants.IS_READ_ONE, false);
						intent.putExtra("current", 3);
					} else if (type == 1) {
						SPUtils.put(App.ctx, null, SPContants.IS_READ_TWO, false);
						intent.putExtra("current", 4);
					}
					startActivity(intent);
				} else if (msg.activity.equals("order_message")) {
					try {
						jsonObject = msg.getRaw().getJSONObject("extra");
						jsonObject = jsonObject.getJSONObject("after_open");
						order_code = jsonObject.getString("order_code");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Intent intent = new Intent(getApplicationContext(),
							WebActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					String url = NetPublicConstant.WEB_URL+"/Express/viewOrder?order_code="
							+ order_code;
					System.out
							.println("model.getExtra().getafterOpen().getOrderCode()"
									+ order_code);
					intent.putExtra("url", url);
					intent.putExtra("title", "订单通知");
					startActivity(intent);

				} else if (msg.activity.equals("system_message")) {
					try {
						jsonObject = msg.getRaw().getJSONObject("extra");
						jsonObject = jsonObject.getJSONObject("after_open");
						id = jsonObject.getString("id");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Intent intent = new Intent(getApplicationContext(),
							UpdatePhoneActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(
							"url",
							baseUrl
									+ "id="
									+ id
									+ "&psw="
									+ SPUtils.get(App.ctx, null,
											SPContants.PASSWORD, "")
									+ ""
									+ "&uid="
									+ SPUtils.get(App.ctx, null,
											SPContants.USER_ID, "") + "");
					intent.putExtra("title", "我的消息");
					startActivity(intent);
				}
			}
		};

		// 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
		// 参考http://bbs.umeng.com/thread-11112-1-1.html
		// CustomNotificationHandler notificationClickHandler = new
		// CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);

		// if (MiPushRegistar.checkDevice(this)) {
		// MiPushRegistar.register(this, "2882303761517400865",
		// "5501740053865");
		// }

	}

	public void showNetWorkError() {
		if (toast == null) {
			toast = Toast.makeText(App.ctx, "", 1);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.setView(LayoutInflater.from(App.ctx).inflate(
					R.layout.dialog_network_error, null));
		}

		toast.show();
	}

	public void addActivity(Activity activity) {
		activityList.add(new WeakReference<Activity>(activity));
	}

	// 遍历所有Activity并finish
	public void exit() {
		for (WeakReference<Activity> activity : activityList) {
			if (activity.get() != null) {
				activity.get().finish();
			}

		}
		System.exit(0);
	}


	


}
